<?php

namespace common\tools;

/**
 * Desc 实用工具类
 * * */
class Util {

    /**
     * 获取分页 
     * @param  int    $page  
     * @param  int $limit 
     * @return array              
     */
    public static function getLimit($page, $limit = 20) {
        return [(($page - 1) < 0 ? 0 : $page - 1) * $limit, $limit];
    }

    /**
     * @desc 传两个时间(时间戳)获取连续时间
     * @return string
     * */
    public static function getDatesByTimes($stime, $etime,$type = 1) {
        if ($stime > $etime) {
            return [];
        }

        $day = round(($etime - $stime) / 86400);

        $dates[] = date($type == 1?'Y-m-d':'m-d', $stime);

        for ($i = 1; $i < $day; $i++) {
            $dates[] = date($type == 1?'Y-m-d':'m-d', strtotime("+{$i} day", $stime));
        }
        $dates[] = date($type == 1?'Y-m-d':'m-d', $etime);
        return array_unique($dates);
    }

    /**
     * @desc 递归获取树状数组
     * @return string
     * */
    public static function arrayTree($ary = [], $parent_id = 0, $level = 10, $i = 1) {
        $arr = [];
        foreach ($ary as &$rs) {
            if ($rs['parent_id'] != $parent_id) {
                continue;
            }
            if ($i > $level) {
                break;
            }
            $arr[$rs['id']] = $rs;
            $n = $i;
            $n++;
            $children = self::arrayTree($ary, $rs['id'], $level, $n);
            if($children){
                $arr[$rs['id']]['children'] = $children;
            }
        }
        if ($arr) {
            $arr = array_values($arr);
        }
        return $arr;
    }
    
    /**
     * 获取IP
     * **/
    public static function getIp(){
        return php_sapi_name() == 'cli'?'127.0.0.1':\Yii::$app->request->userIP;
    }
    
    /**
     * 创建目录
     * * */
    public static function mkdir($dir) {
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
    }

}
